<template>
  <div class="login">
    <el-form
      ref="loginRef"
      :model="resetForm"
      :rules="resetRules"
      class="login-form"
      label-position="top"
    >
      <h3 class="title">忘记密码</h3>
      <el-form-item prop="email" label="邮箱" width="100">
        <el-input
          v-model="resetForm.email"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="邮箱"
        >
          <template #prefix
            ><svg-icon icon-class="email" class="el-input__icon input-icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="emailcode" label="验证码" width="100">
        <el-input
          v-model="resetForm.emailcode"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="邮箱验证码"
          @keyup.enter="handleLogin"
          style="width: 77%; margin-right: 3%"
        >
          <template #prefix
            ><svg-icon icon-class="validCode" class="el-input__icon input-icon"
          /></template>
        </el-input>
        <el-button
          size="large"
          type="primary"
          style="width: 20%"
          @click.prevent="handleSend"
          :disabled="codetxt != '发送验证码'"
          :loading="emailloading"
        >
          <span>{{ codetxt }}</span>
        </el-button>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="resetForm.code"
          size="large"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter="handleLogin"
        >
          <template #prefix
            ><svg-icon icon-class="validCode" class="el-input__icon input-icon"
          /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width: 100%"
          @click.prevent="handleLogin"
          :disabled="btntxt != '重置密码'"
        >
          <span v-if="!loading">{{ btntxt }}</span>
          <span v-else>重置中</span>
        </el-button>
        <div style="color: #409eff; cursor: pointer" @click="goLogin">
          返回登录界面
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <!-- <div class="el-login-footer">
      <p>AI智慧学习中心</p>
      <p>Copyright© 2023 </p>
      <p>华东师范大学商业分析实验教学中心</p>
    </div> -->
    <Footer class="el-login-footer"></Footer>
  </div>
</template>

<script setup>
import { getCodeImg, getEmailCode, sendEmailCode } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";
import Footer from "@/homeLayout/components/Footer.vue";

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const resetForm = ref({
  email: "",
  code: "",
  emailcode: "",
});
let emailcodeRequired = false;
const validateEmailCode = (rule, value, callback) => {
  if (emailcodeRequired && (value === "" || value == undefined)) {
    callback(new Error("请输入邮箱验证码"));
  } else {
    callback();
  }
};
const resetRules = {
  email: [{ required: true, trigger: "blur", message: "请输入您的邮箱" }],
  emailcode: [
    {
      validator: validateEmailCode,
      trigger: "blur",
    },
  ],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

const codeUrl = ref("");
const loading = ref(false);
const emailloading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);
const btntxt = ref("重置密码");
const codetxt = ref("发送验证码");
const countdown = ref(60);

watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

function goLogin() {
  router.push({ path: "/login" });
}

function handleLogin() {
  emailcodeRequired = true;
  loading.value = true;
  proxy.$refs.loginRef.validate((valid) => {
    sendEmailCode({
      email: resetForm.value.email,
      code: resetForm.value.emailcode,
    })
      .then((res) => {
        proxy.$modal.msgSuccess(res.msg);
        btntxt.value = res.msg;
        loading.value = false;
        router.push({ path: "/login" });
      })
      .catch(() => {
        loading.value = false;
      });
  });
}

function getCode() {
  getCodeImg().then((res) => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      resetForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  resetForm.value = {
    username: username === undefined ? resetForm.value.username : username,
    password:
      password === undefined ? resetForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}

//发送邮箱验证码
function handleSend() {
  emailloading.value = true;
  emailcodeRequired = false;
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      getEmailCode({ email: resetForm.value.email }).then((res) => {
        emailloading.value = false;
        proxy.$modal.msgSuccess(res.msg);
        codetxt.value = countdown.value;
        const timer = setInterval(() => {
          if (countdown.value > 0) {
            countdown.value--;
            codetxt.value = countdown.value;
          } else {
            clearInterval(timer); // 倒计时结束，清除定时器
            countdown.value = 60;
            codetxt.value = "发送验证码";
          }
        }, 1000); // 每秒更新一次
      });
    }
  });
}
//跳转外链
function jumpLink() {
  let url =
    "https://sso.ecnu.edu.cn/login?service=https:%2F%2Fapi.ecnu.edu.cn%2Fuser%2Fauthorize";
  window.open(url);
}
getCode();
getCookie();
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: right;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/register-bg.png");
  background-size: cover;
  background-position-y: -150px;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #046ded;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 500px;
  padding: 35px 35px 35px 35px;
  margin-right: 20vw;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  position: fixed;
  bottom: 0;
  width: 100%;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
.login-text {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #409eff;
}
</style>
